<template>
  <div class="app-container">
    <div class="el-toolbar">
      <div class="el-toolbar-body" style="justify-content: flex-start; margin-bottom: 15px">
        <el-button type="primary" @click="exportData" icon="el-icon-download">导出</el-button>
        <el-button type="primary" @click="importData" icon="el-icon-upload2">导入</el-button>
      </div>
    </div>

    <el-table
      :data="list"
      v-loading="loading"
      element-loading-text="正在努力加载数据中..."
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      style="width: 100%"
      max-height="500px"
      row-key="id"
    >
      <el-table-column label="分类名称" prop="name" min-width="250" align="left" />
      <el-table-column label="分类图片" prop="imageUrl" min-width="150">
        <template v-slot="scope">
          <el-image
            :src="scope.row.imageUrl"
            :preview-src-list="[scope.row.imageUrl]"
            style="width: 60px; height: 60px"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="分类描述" prop="description" align="left" />
      <el-table-column label="创建时间" prop="createTime" min-width="160" align="center" />
    </el-table>

    <el-dialog title="导入" :visible.sync="dialogImportVisible" width="480px">
      <el-form label-position="right" label-width="170px">
        <el-form-item label="文件">
          <el-upload
            ref="uploadRef"
            :multiple="false"
            :on-success="onUploadSuccess"
            :action="'http://localhost:8000/file/upload'"
            class="upload-demo"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传xls文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogImportVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import categoryApi from '@/api/category'

export default {
  data() {
    // 初始化数据
    return {
      loading: true, // 加载动画
      list: [],
      dialogImportVisible: false // 弹框显示
    }
  },
  created() {
    this.getCategoryList()
  },
  methods: {
    // 数据字典列表
    getCategoryList() {
      categoryApi.getCategory().then((res) => {
        this.list = res.data
        this.loading = false
      })
    },

    // 导出
    exportData() {
      window.location.href = 'http://localhost:8000/category/exportData'
    },

    // 导入
    importData() {
      // 设置弹出层显示
      this.dialogImportVisible = true
    },

    //当上传成功后执行的回调函数
    onUploadSuccess(res, file) {
      categoryApi.importData(res.data).then((res) => {
        this.$refs.uploadRef.clearFiles()
        this.dialogImportVisible = false
        this.$message.success('上传成功')
        this.getCategoryList()
      })
    }
  }
}
</script>

<style></style>
